package com.jxdinfo.hussar.example.common.schedulingtask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxdinfo.hussar.example.common.schedulingtask.dao.MdUnitMeasureMapper;
import com.jxdinfo.hussar.example.common.schedulingtask.model.MdUnitMeasure;
import com.jxdinfo.hussar.example.common.schedulingtask.service.MdUnitMeasureService;
import com.jxdinfo.hussar.example.common.schedulingtask.vo.MdUnitMeasureVO;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author QiaoBin
 * @Date 2024/4/02 15:49
 * @Description md_unit_measure单位表的定时任务
 */
@Component
@AllArgsConstructor
public class MdUnitMeasureScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(MdUnitMeasureScheduleTask.class);

    private MdUnitMeasureMapper mdUnitMeasureMapper;
    private MdUnitMeasureService mdUnitMeasureService;

//    @Scheduled(cron = "*/5 * * * * ?")
    @Scheduled(cron = "0 30 2 * * ?") // 每天凌晨2点30执行
    public void mdUnitMeasureTask() {
        logger.info("\n用友-单位表-定时任务-开始执行");
        LocalDateTime nowTime = LocalDateTime.now();
        synchronized ("mdUnitMeasureTask") {
            logger.info("用友-单位表-开始查询单位表中最大的同步时间");
            LocalDateTime scheduleDate = mdUnitMeasureMapper.selectMaxScheduleDate();
            String scheduleDateString = "";
            if (scheduleDate != null) {
                scheduleDateString = scheduleDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            //查询创建时间大于定时任务时间，查询出来后把所有数据全部插进去
            logger.info("\n用友-单位表-开始查询md_unit_measure表中创建时间大于任务时间的数据,查询参数scheduleDateString={}", scheduleDateString);
            List<MdUnitMeasureVO> moreUnitMeasureList = mdUnitMeasureMapper.selectMoreSchedule(scheduleDateString);
            logger.info("\n用友-单位表-结束查询md_unit_measure表中创建时间大于任务时间的数据,查询结果moreUnitMeasureList={}，size={}", moreUnitMeasureList, moreUnitMeasureList.size());
            if (moreUnitMeasureList.size() > 0) {
                ArrayList<MdUnitMeasure> mdUnitMeasureList = new ArrayList<>();
                for (int i = 0; i < moreUnitMeasureList.size(); i++) {
                    logger.info("\n用友-单位表-当前循环次数i={}", i);
                    MdUnitMeasureVO mdUnitMeasureVO = moreUnitMeasureList.get(i);
                    MdUnitMeasure mdUnitMeasure = new MdUnitMeasure();
                    mdUnitMeasure.setMeasureId(mdUnitMeasureVO.getMeasureId());
                    mdUnitMeasure.setMeasureCode(mdUnitMeasureVO.getMeasureCode());     // 编码
                    mdUnitMeasure.setMeasureName(mdUnitMeasureVO.getMeasureName());     // 名称
                    mdUnitMeasure.setPrimaryFlag(mdUnitMeasureVO.getPrimaryFlag());     // 是否是主单位
                    mdUnitMeasure.setChangeRate(mdUnitMeasureVO.getChangeRate());     // 与主单位换算比例
                    mdUnitMeasure.setEnableFlag(mdUnitMeasureVO.getEnableFlag());     // 是否启用
                    mdUnitMeasure.setScheduleTime(nowTime);
                    mdUnitMeasure.setCreateBy(mdUnitMeasureVO.getCreateBy());
                    mdUnitMeasure.setCreateTime(mdUnitMeasureVO.getCreateTime());
                    mdUnitMeasure.setUpdateBy(mdUnitMeasureVO.getUpdateBy());
                    mdUnitMeasure.setUpdateTime(mdUnitMeasureVO.getUpdateTime());
                    mdUnitMeasure.setErpUnitId(mdUnitMeasureVO.getMeasureId());
                    logger.info("\n用友-单位表-开始向list中存入数据，数据mdUnitMeasure={},i={}", mdUnitMeasure, i);
                    mdUnitMeasureList.add(mdUnitMeasure);
                }
                logger.info("\n用友-单位表-开始向md_unit_measure表中插入数据，数据mdUnitMeasureList={}", mdUnitMeasureList);
                boolean b = mdUnitMeasureService.saveBatch(mdUnitMeasureList, 100);
                logger.info("\n用友-单位表-结束向md_unit_measure表中插入数据，插入结果b={}", b);
            }
            if (scheduleDate == null) {
                logger.info("\n用友-单位表-查询不到任务时间，说明一次也没有同步，之间原封不动的插入就行,也就不需要后续更新");
                return;
            }
            if (scheduleDate != null) {
                logger.info("\n用友-单位表-开始查询md_unit_measure表中更新时间大于任务时间，查询参数scheduleDateString={}", scheduleDateString);
                List<MdUnitMeasureVO> moreUpdateUnitMeasureList = mdUnitMeasureMapper.selectUpdateMoreSchedule(scheduleDateString);
                logger.info("\n用友-单位表-结束查询md_unit_measure表中更新时间大于任务时间,查询结果moreUpdateUnitMeasureList={},数量size={}", moreUpdateUnitMeasureList, moreUpdateUnitMeasureList.size());

                if (moreUpdateUnitMeasureList == null || moreUpdateUnitMeasureList.size() == 0) {
                    logger.info("\n用友-单位表-没有查询到更新时间大于任务时间的md_unit_measure表中数据");
                    return;
                }
                // 转成map集合
                logger.info("\n用友-单位表-开始把用友表中更新时间大于任务时间的数据转换成主键、对象的map集合");
                Map<Long, MdUnitMeasureVO> mdUnitMeasureUpdateMap = moreUpdateUnitMeasureList.stream().collect(Collectors.toMap(MdUnitMeasureVO::getMeasureId, t -> t));
                logger.info("\n用友-单位表-开始获取用友表中更新时间大于任务时间的数据的主键");
                List<Long> unitMeasureIdList = moreUpdateUnitMeasureList.stream().map(MdUnitMeasureVO::getMeasureId).collect(Collectors.toList());
                logger.info("\n用友-单位表-md_unit_measure表更新时间大于任务时间的主键集合unitMeasureIdList={},size={}", unitMeasureIdList, unitMeasureIdList.size());

                logger.info("\n用友-单位表-开始查询md_unit_measure中erp_unit_id=erp表中主键的数据,参数unitMeasureIdList={}", unitMeasureIdList);
                QueryWrapper<MdUnitMeasure> mdUnitMeasureQueryWrapper = new QueryWrapper<>();
                mdUnitMeasureQueryWrapper.in("erp_unit_id",unitMeasureIdList);
                mdUnitMeasureQueryWrapper.eq("deleted_flag",0);
                List<MdUnitMeasure> mdUnitMeasureUpdateList = mdUnitMeasureMapper.selectList(mdUnitMeasureQueryWrapper);
                logger.info("\n用友-单位表-结束查询md_unit_measure中erp_unit_id=erp表中主键的数据,结果mdUnitMeasureUpdateList={},size={}", mdUnitMeasureUpdateList, mdUnitMeasureUpdateList.size());
                if (mdUnitMeasureUpdateList.size() > 0) {
                    ArrayList<MdUnitMeasure> updateMdUnitMeasureList = new ArrayList<>();
                    for (int i = 0; i < mdUnitMeasureUpdateList.size(); i++) {
                        logger.info("\n用友-单位表-当前更新时间大于任务时间，md_unit_measure表更新，次数i={}", i);
                        MdUnitMeasure mdUnitMeasure = mdUnitMeasureUpdateList.get(i);
                        Long currentMasterId = mdUnitMeasure.getErpUnitId();
                        MdUnitMeasureVO mdUnitMeasureVO = mdUnitMeasureUpdateMap.get(currentMasterId);
                        mdUnitMeasure.setMeasureCode(mdUnitMeasureVO.getMeasureCode());              // 编码
                        mdUnitMeasure.setMeasureName(mdUnitMeasureVO.getMeasureName());              // 名称
                        mdUnitMeasure.setEnableFlag(mdUnitMeasureVO.getEnableFlag());              // 生效状态
                        mdUnitMeasure.setChangeRate(mdUnitMeasureVO.getChangeRate());     // 与主单位换算比例
                        mdUnitMeasure.setEnableFlag(mdUnitMeasureVO.getEnableFlag());     // 是否启用
                        mdUnitMeasure.setScheduleTime(nowTime);
                        mdUnitMeasure.setCreateBy(mdUnitMeasureVO.getCreateBy());
                        mdUnitMeasure.setCreateTime(mdUnitMeasureVO.getCreateTime());
                        mdUnitMeasure.setUpdateBy(mdUnitMeasureVO.getUpdateBy());
                        mdUnitMeasure.setUpdateTime(mdUnitMeasureVO.getUpdateTime());
                        logger.info("\n用友-单位表-向updateMdUnitMeasureList存储待要更新的单位表信息,mdUnitMeasure={}", mdUnitMeasure);
                        updateMdUnitMeasureList.add(mdUnitMeasure);
                    }
                    logger.info("\n用友-单位表-开始更新md_unit_measure数据,列表updateMdUnitMeasureList={}", updateMdUnitMeasureList);
                    boolean u = mdUnitMeasureService.updateBatchById(updateMdUnitMeasureList);
                    logger.info("\n用友-单位表-结束更md_unit_measure数据,更新结果u={}", u);
                }
            }
        }
        logger.info("\n用友-单位表-定时任务-结束执行");
    }
}
